﻿using System;
using System.Linq;
using Avalonia.Input;
using Avalonia.Threading;
using MusicFluent.Models;
using MusicFluent.ViewModels;
using MusicFluent.ViewModels.Pages;
using MusicFluent.Views;
using NetEasyMusic.Lib.Details;
using NetEasyMusic.Lib.Models;

namespace MusicFluent.Pages;

public partial class HomeView : PageViewBase
{
    public HomeView()
    {
        InitializeComponent();
    }

    private BannerModel[] _banners = [];

    protected override async void OnInitialized()
    {
        var main = ViewOpera.GetView<MainWindow>(this);
        main?.TaskShow();
        if (DataContext is not HomeViewModel model) return;
        _banners = await model.Personalized.Banner();
        Carousel.ItemsSource = _banners;
        PlaylistItems.ItemsSource = await model.Personalized.RecommendPlaylist();
        main?.TaskShow();
        StartAutoSwitchTimer();
    }

    private void StartAutoSwitchTimer()
    {
        var dispatcherTimer =
            new DispatcherTimer(TimeSpan.FromSeconds(5), DispatcherPriority.Normal, AutoSwitchTimerCallback);
        dispatcherTimer.Start();
    }

    private async void AutoSwitchTimerCallback(object? sender, EventArgs e)
    {
        var result = await Dispatcher.UIThread.InvokeAsync(() => Carousel.SelectedIndex);
        Dispatcher.UIThread.Post(() =>
            Carousel.SelectedIndex = (result + 1) % (_banners.Length == 0 ? 1 : _banners.Length));
    }

    private async void FmTapped(object? sender, TappedEventArgs e)
    {
        var view = ViewOpera.GetView<MainWindow>(this);
        if (view == null) return;
        view.TaskShow();
        if (DataContext is not HomeViewModel home) return;
        var musics = await home.Personalized.FM();
        var _model = musics.FirstOrDefault();
        if (_model == null) return;
        view.SongPanel.DataContext = _model;
        if (view.DataContext is not MainWindowViewModel model) return;
        model.Add(musics);
        model.PlayChange(_model.Id);
        view.TaskShow();
    }

    private async void SongTapped(object? sender, TappedEventArgs e)
    {
        var view = ViewOpera.GetView<MainWindow>(this);
        if (view == null) return;
        view.TaskShow();
        if (DataContext is not HomeViewModel home) return;
        var musics = await home.Personalized.RecommendSong();
        var playlist = new MusicViews.PlaylistView(new PlaylistDetailModel()
        {
            Musics = musics.ToList(), Name = "每日歌曲推荐"
        });
        view.Navigate(playlist);
        view.TaskShow();
    }
}